<template>
  <div class="order-container">
    <div class="search-section animate__animated animate__fadeInDown">
      <el-input style="width: 200px;margin-right: 20px" placeholder="请输入订单号" v-model="orderNo" prefix-icon="el-icon-search"></el-input>
      <el-button style="margin-left: 10px;" type="primary" @click="load" class="el-icon-search">搜索</el-button>
      <el-button style="margin-left: 10px;" type="warning" @click="reset" class="el-icon-refresh">重置</el-button>
      <el-button style="margin-left: 20px;" type="info" icon="el-icon-s-home" @click="goHome">返回主页</el-button>
    </div>

    <div v-if="roleId === 3" class="role-notice animate__animated animate__fadeIn">
      <el-alert
        title="提示：普通用户无法修改订单配送状态，请联系管理员处理"
        type="info"
        show-icon
        :closable="false">
      </el-alert>
    </div>

    <div class="table-section animate__animated animate__fadeInUp">
      <el-table
          :data="tableData" border stripe
          :header-cell-style="getRowClass"
          @selection-change="handleSelectionChange"
          row-key="id">
        
        <el-table-column prop="orderId" label="订单号"></el-table-column>
        <el-table-column prop="totalAmount" label="总金额"></el-table-column>
        <el-table-column prop="orderStatus" label="订单状态">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.orderStatus)">
              {{ getStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryAddress" label="收货地址"></el-table-column>
        <el-table-column prop="traceCode" label="溯源码"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <div class="operation-buttons">
              <el-button size="mini" type="primary" class="el-icon-view" @click="handleView(scope.row)">查看</el-button>
              <el-button size="mini" type="success" class="el-icon-check" @click="handlePay(scope.row)" v-if="scope.row.orderStatus === 0">支付</el-button>
              <el-button size="mini" type="danger" class="el-icon-close" @click="handleCancel(scope.row)" v-if="scope.row.orderStatus === 0">取消</el-button>
              <el-button size="mini" type="warning" class="el-icon-s-promotion" @click="handleDelivery(scope.row, true)" v-if="scope.row.orderStatus === 1 && roleId !== 3">配送</el-button>
              <el-button size="mini" type="info" class="el-icon-s-release" @click="handleDelivery(scope.row, false)" v-if="scope.row.orderStatus === 2 && roleId !== 3">取消配送</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="padding:10px 0;align-content: center;margin-left: 30%;margin-top:30px;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="订单详情" :visible.sync="dialogFormVisible" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ form.orderId }}</el-descriptions-item>
        <el-descriptions-item label="总金额">{{ form.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(form.orderStatus)">
            {{ getStatusText(form.orderStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ form.deliveryAddress }}</el-descriptions-item>
        <el-descriptions-item label="溯源码">{{ form.traceCode }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ form.createTime }}</el-descriptions-item>
        <el-descriptions-item label="商品ID">{{ form.productId }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ form.quantity }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'animate.css/animate.min.css';

export default {
  name: "Order",
  data() {
    return {
      pageSize: 10,
      pageNum: 1,
      orderNo: '',
      tableData: [],
      dialogFormVisible: false,
      form: {},
      multipleSelection: [],
      total: 0,
      userId: 1,
      roleId: 1
    }
  },
  created() {
    const userInfo = localStorage.getItem("user");
    if (userInfo) {
      const user = JSON.parse(userInfo);
      this.userId = user.id || 1;
      this.roleId = user.roleId || 1;
    }
    this.load();
  },
  methods: {
    load() {
      console.log("发送请求参数:", {
        orderNo: this.orderNo,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        userId: this.userId,
        roleId: this.roleId
      });
      
      this.request.get("/order/findAll", {
        params: {
          orderNo: this.orderNo,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          userId: this.userId,
          roleId: this.roleId
        }
      }).then(res => {
        console.log("接收到响应:", res);
        if (res.code === '200') {
          this.tableData = res.data.records || [];
          this.tableData.forEach(item => {
            item.orderId = item.id;
            item.totalAmount = item.totalPrice;
            item.orderStatus = item.status;
          });
          this.total = res.data.total || 0;
        } else {
          console.error("请求失败:", res.msg);
        }
      }).catch(err => {
        console.error("请求异常:", err);
      });
    },
    getRowClass({rowIndex, columnIndex}) {
      if(rowIndex === 0) {
        return 'background:#ccc'
      }
    },
    reset() {
      this.orderNo = '';
      this.load();
    },
    handleView(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogFormVisible = true;
    },
    handlePay(row) {
      this.$confirm('确认支付该订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.post("/order/pay/" + row.orderId).then(res => {
          if (res.code === '200') {
            this.$message.success('支付成功');
            this.load();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    handleCancel(row) {
      this.$confirm('确认取消该订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.post("/order/cancel/" + row.orderId).then(res => {
          if (res.code === '200') {
            this.$message.success('取消成功');
            this.load();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    handleDelivery(row, toDelivery) {
      const action = toDelivery ? '配送' : '取消配送';
      this.$confirm(`确认${action}该订单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.post(`/order/updateDelivery/${row.orderId}?toDelivery=${toDelivery}&userId=${this.userId}&roleId=${this.roleId}`).then(res => {
          if (res.code === '200') {
            this.$message.success(`${action}成功`);
            this.load();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.load();
    },
    getStatusType(status) {
      const types = {
        0: 'info',
        1: 'success',
        2: 'warning',
        3: 'primary',
        4: 'danger'
      };
      return types[status] || 'info';
    },
    getStatusText(status) {
      const texts = {
        0: '待支付',
        1: '已支付',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      };
      return texts[status] || '未知状态';
    },
    goHome() {
      this.$router.push('/home');
    }
  }
}
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.role-notice {
  margin-bottom: 20px;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.operation-buttons {
  display: flex;
  gap: 5px;
}

.el-button {
  margin: 0;
}

.el-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style> 